var xml2js 			= require('xml2js');
var avUserCoupon	= AV.Object.extend("UserCoupon");
var avCoupon		= AV.Object.extend("Coupon");
var avExtendQRCode	= AV.Object.extend("ExtendQRCode");
/*
	函数库
*/
exports.appID		= "wxea723b455c66864d"//"wx850fb2baa171a808""wxea723b455c66864d";
exports.appsecret	= "52e627569c0567f15d69d41f8fc76814"//"3b3bc8d153e9327a0f5b58a5b246e70b""52e627569c0567f15d69d41f8fc76814";
exports.access_token= "";
exports.ticket		= "";
exports.deadline	= 0;
exports.noncestr	= "kqd";
exports.code		= "";
exports.mch_id		= "1280203101";//微信支付商户号

/**
 * 获取access_token
 * 2015.09.28  by 胡斌
 * @param callback 		回调函数
 */
exports.getToken = function(onSuccess,onError) {
	var timestamp = Date.parse(new Date())/1000;
	if(timestamp<exports.deadline){
		onSuccess();
	}else{
		AV.Cloud.httpRequest({
			url: 'https://api.weixin.qq.com/cgi-bin/token',
			params: {
				grant_type	: 'client_credential',
				appid 		: exports.appID,
				secret 		: exports.appsecret,
			},
			success: function(res){
				exports.access_token	= res.data.access_token;
				exports.deadline		= timestamp+res.data.expires_in-1000;
				exports.ticket			= "";
				onSuccess();
			},
			error: function(res){
				onError(res.data);
			}
		});

	}
}


/**
 * 获取jsapi_ticket
 * 2015.10.14  by 胡斌
 * @param callback 		回调函数
 */
exports.getTicket = function(onSuccess,onError) {
	var timestamp = Date.parse(new Date())/1000;

	if(exports.ticket.length>1 && timestamp<exports.deadline){
		onSuccess();
	}else{
		exports.getToken(function(){
			AV.Cloud.httpRequest({
				url: 'https://api.weixin.qq.com/cgi-bin/ticket/getticket',
				params: {
					access_token: exports.access_token,
					type 		: 'jsapi'
				},
				success: function(res){
					//console.dir(res.data);
					exports.ticket	= res.data.ticket;
					onSuccess();
				},
				error: function(res){
					onError(res.data);
				}
			});
		},function(data){
			//console.dir(res);
			//if(res.data)
			onError(data);
		});
	}
}

/**
 * 发送业务消息
 * 2015.11.06  by 胡斌
 * @param callback 		回调函数
 */
exports.sendMessage = function(user, data) {
	//console.log(exports.appID);
	//res.send(exports);
	//exports.sendMessage(user,data);
	exports.getToken(function(){
		AV.Cloud.httpRequest({
			method: 'POST',
			url: 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='+exports.access_token,
			headers: {'Content-Type': 'application/json'},
			body: {
				touser:user.get('authData').weixin.openid,
				template_id : data.template,
				url:data.url,
				topcolor:"#FF0000",
				data:{
					first: {
						value: "你的订单已支付成功！ 订单编号："+data.number,
						color: "#173177"
					},
					orderMoneySum: {
						value: "￥"+Math.round(data.money*100)/100,
						color: "#173177"
					},
					orderProductName: {
						value: data.title,
						color: "#173177"
					},
					Remark: {
						value: "【地址】"+data.address+"【使用日期】"+data.date+" 【咨询电话】"+data.phone+" 【验证码】"+data.code,
						color: "#111111"
					}
				}
			},
			success: function(data){
				if(data && data.text && data.text.errcode){
					console.error(data.text.errmsg);
				}
			},
			error: function(err){
				console.error(err.errcode);
			}
		});
	},function(err){
		console.error(err.errmsg);
	});
}

/**
 * 发送业务通知
 * 2015.11.06  by 胡斌
 * @param callback 		回调函数
 */
exports.sendwxMessage = function(user, data) {
	exports.getToken(function(){
		AV.Cloud.httpRequest({
			method: 'POST',
			url: 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='+exports.access_token,
			headers: {'Content-Type': 'application/json'},
			body: {
				touser:user.get('authData').weixin.openid,
				template_id : data.template,
				url:data.url,
				topcolor:"#FF0000",
				data:data.data
			},
			success: function(data){
				//console.dir(data);
				if(data && data.text && data.text.errcode){
					console.error(data.text.errmsg);
				}
			},
			error: function(err){
				console.error(err.errcode);
			}
		});
	},function(err){
		console.error(err.errmsg);
	});
}

/**
 * 获取用户推广二维码
 * 2015.11.06  by 胡斌
 * @param callback 		回调函数
 */
exports.getUserShareCode = function(user,onSuccess) {
	var returnData;
	var shareData=user.get("shareData");
	var now=Math.round(new Date().getTime()/1000);
	if(shareData && shareData.deadline>now){
		onSuccess(shareData.url);
	}else{
		returnData={url:"http://ac-0s7lcch8.clouddn.com/94eb59e7f43ae5a7.jpg",deadline:now};
		exports.getToken(function(){
			AV.Cloud.httpRequest({
				method: 'POST',
				url: 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='+exports.access_token,
				headers: {'Content-Type': 'application/json'},
				body: {
					expire_seconds:604800,
					action_name:"QR_LIMIT_STR_SCENE",
					action_info:{"scene":{"scene_str":user.id}}
				},
				success: function(data){
					//console.dir(data);

					if(data && data.text && data.text.errcode){
						console.error(data.text.errmsg);
					}
					if(data && data.data && data.data.ticket){
						returnData={url:"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+data.data.ticket,deadline:now+data.data.expire_seconds};
						var authData=user.get("authData");
						if(authData && authData.weixin && authData.weixin.openid){
							user.set("openid",authData.weixin.openid);
						}
						//console.dir(returnData);
						user.set("shareData",returnData);
						user.save();
					}
					onSuccess(returnData.url);
				},
				error: function(err){
					console.error(err.errcode);
				}
			});
		},function(err){
			onSuccess(returnData.url);
		});
	}
}

/**
 * 获取用户推广二维码
 * 2015.11.06  by 胡斌
 * @param callback 		回调函数
 */
exports.getUserShareCode2 = function(ExtendQRCode,onSuccess,onError) {
		if(ExtendQRCode.get("ticket")){
			onSuccess("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ExtendQRCode.get("ticket"));
		}else{
			exports.getToken(function(){
				//console.log(ExtendQRCode.get("sn"));
				//console.log(ExtendQRCode.get("sn")+1000+"");
				AV.Cloud.httpRequest({
					method: 'POST',
					url: 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='+exports.access_token,
					headers: {'Content-Type': 'application/json'},
					body: {
						expire_seconds:604800,
						action_name:"QR_LIMIT_STR_SCENE",
						action_info:{"scene":{"scene_str":ExtendQRCode.get("sn")+1000+""}}
					},
					success: function(data){
						if(data && data.text && data.text.errcode){
							console.error(data.text.errmsg);
							onError(data.text.errmsg);
						}else if(data && data.data && data.data.ticket){
							ExtendQRCode.set("ticket",data.data.ticket);
							ExtendQRCode.save();
							onSuccess("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+data.data.ticket);
						}
					},
					error: function(err){
						console.error(err.errcode);
						onError(err.errcode);
					}
				});
			},function(err){
				onError("授权参数错误！");
			});
		}
}

/**
 * 获取signature
 * 2015.10.14  by 胡斌
 * @param timestamp 时间戳
 */
exports.getSignature = function(timestamp,url) {
	var crypto 		= require('crypto');
	var shasum 		= crypto.createHash('sha1');
	shasum.update("jsapi_ticket="+exports.ticket+"&noncestr="+exports.noncestr+"&timestamp="+timestamp+"&url="+url);
	//console.log(url);

	return shasum.digest('hex');
}

/**
 * 获取access_token
 * 2015.09.28  by 胡斌
 * @param callback 		回调函数
 */
exports.getUserInfo = function(user){
	exports.getToken(function(){
	var authData=user.get("authData");
		AV.Cloud.httpRequest({
			url: 'https://api.weixin.qq.com/cgi-bin/user/info',
			params: {
				lang		: 'zh_CN',
				access_token: exports.access_token,
				openid 		: authData.weixin.openid,
			},
			success: function(res){
				user.set("nickname",res.data.nickname);
				user.set("sex",res.data.sex);
				user.set("city",res.data.city);
				user.set("province",res.data.province);
				user.save();

				if(res.data.headimgurl){
					var file = AV.File.withURL('headimg_'+res.data.openid+'.jpg', res.data.headimgurl);
					file.save().then(function(file) {
						user.set("headimg",file);
						user.save();
					});
					AV.Cloud.httpRequest({ url: res.data.headimgurl }).then(function(response) {
						var file = new AV.File('headimg_'+res.data.openid+'.jpg',response.buffer);
						file.save().then(function(file) {
							user.set("headimg",file);
							user.save();
						});
					});
				}
			},
			error: function(res){}
		});
	},function(err){
		console.error(err);
	})
}

/**
 * 微信认证
 * 2015.09.28  by 胡斌
 */
exports.checkUrl = function(req,res){
	//console.log("1111");
	var crypto 		= require('crypto');
	var shasum 		= crypto.createHash('sha1');
	var signature 	= req.query.signature
       ,timestamp 	= req.query.timestamp
       ,nonce 		= req.query.nonce
	   ,echostr 	= req.query.echostr;
	var tmpArr		= [timestamp,nonce,'kqd'];
	var newArr		= tmpArr.sort();
	var tmpStr		= newArr.join('');

	shasum.update(tmpStr);
	if(shasum.digest('hex')===signature){
		res.send(echostr);
	}else{
		res.send("error");
	}
}

/**
 * 微信认证
 * 2015.09.28  by 胡斌
 */
exports.checkUrl2 = function(req,res){
	//console.log("222");
	//console.dir(req);
	var json={};
	req.rawBody = '';
	req.setEncoding('utf8');
	req.on('data', function(chunk) {
		req.rawBody += chunk;
	});
	req.on('end', function() {
		var parseString = xml2js.parseString;
		//console.log(req.rawBody);
		parseString(req.rawBody,{explicitArray : false}, function(err, data) {
			//console.dir(data.xml);
			if(data && data.xml.MsgType=="event"){
				if(data.xml.Event=="CLICK"){
					if(data.xml.EventKey=="V2016_NEW_2DCODE"){
						//console.log(data.xml.EventKey);
						res.send("<xml><ToUserName>"+data.xml.FromUserName+"</ToUserName><FromUserName>"+data.xml.ToUserName+"</FromUserName><CreateTime>"+Math.round(new Date().getTime()/1000)+"</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>1</ArticleCount><Articles><item><Title><![CDATA[快趣订“友转粉丝换取现金优惠”活动]]></Title> <Description><![CDATA[“是时候出卖朋友了，用朋友换取现金优惠”，分享快趣订个人粉丝页，让好友成功成为自己粉丝换取现金优惠。”]]></Description><PicUrl><![CDATA[https://mmbiz.qlogo.cn/mmbiz/eGnI8NERWePw1jY2KaAADzIqdZ3gYlnsWqjYvulbiaVmKEAvLq2BYBSyDLH4ZPIGJhdRnOSg9y7jicXtIHhMansQ/0?wx_fmt=jpeg]]></PicUrl><Url><![CDATA[http://z.maka.im/pcviewer/69CTF640?DSCKID=14f517aa-d7ed-4de3-b1e0-f0f75afd1adf&DSTIMESTAMP=1454403400427]]></Url></item></Articles></xml>");
						/*res.send("<xml><ToUserName>"+data.xml.FromUserName+"</ToUserName><FromUserName>"+data.xml.ToUserName+"</FromUserName><CreateTime>"+Math.round(new Date().getTime()/1000)+"</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[活动还未开始，敬请期待！]]></Content></xml>");*/
					}else if(data.xml.EventKey=="V3001_CONTACT"){
						res.send("<xml><ToUserName>"+data.xml.FromUserName+"</ToUserName><FromUserName>"+data.xml.ToUserName+"</FromUserName><CreateTime>"+Math.round(new Date().getTime()/1000)+"</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[快趣订，客服电话：075586553283，邮箱：kqd2015@qq.com]]></Content></xml>");
					}else if(data.xml.EventKey=="V3002_COMPLAIN"){
						res.send("<xml><ToUserName>"+data.xml.FromUserName+"</ToUserName><FromUserName>"+data.xml.ToUserName+"</FromUserName><CreateTime>"+Math.round(new Date().getTime()/1000)+"</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[请将您的建议或者投诉，按＃投诉建议＃＋内容的格式回复。感谢您宝贵的意见。]]></Content></xml>");
					}else{
						res.send("success");
					}
				}else if(data.xml.Event=="subscribe" || data.xml.Event=="SCAN"){
					var EventKey=data.xml.EventKey;
					//console.dir(data.xml);
					//console.log(EventKey.length);
					if(EventKey.length>8){
						//console.dir(data.xml);
						var uid=EventKey.replace("qrscene_",""),user;
						var query = new AV.Query(AV.User);
						query.equalTo("objectId",uid);
						query.first().then(function(result){
							user=result;
							if(user){
								var queryUserCoupon = new AV.Query(avUserCoupon);
								queryUserCoupon.equalTo("remark",data.xml.FromUserName);
								return queryUserCoupon.first();
							}else{
								return AV.Promise.error('错误的用户id:'+uid);
							}
						}).then(function(result){
							var myfans=user.get("myfans");
							if(!result && myfans.indexOf(data.xml.FromUserName)==-1){
								user.addUnique('myfans', data.xml.FromUserName);
								user.save();

								var newUserCoupon 	= new avUserCoupon();
								var Coupon 			= new avCoupon();
								Coupon.id			= "56964ccd00b0bca0d5ad8ff8";
								newUserCoupon.set("Coupon",Coupon);
								newUserCoupon.set("uid",user.id);
								newUserCoupon.set("money",5);
								newUserCoupon.set("remark",data.xml.FromUserName);
								newUserCoupon.set("deadline",new Date("2016/04/01"));
								newUserCoupon.save();

								var queryUser = new AV.Query(AV.User);
								queryUser.equalTo("openid",data.xml.FromUserName);
								queryUser.first().then(function(result){
									if(result){
										exports.sendwxMessage(user,{
											template:"fXq_ZRnhzhR279HE0fFYajcAqoxktoHNtLUeDT8WFcY",
											url:"http://kqd.leanapp.cn/client/wd/coupon",
											data:{
												first: {
													value: result.get("nickname")+"成为了你的粉丝，你获得了一张代金券",
													color: "#111111"
												},
												coupon: {
													value: "5元",
													color: "#173177"
												},
												expDate: {
													value: "2016年04月01日",
													color: "#173177"
												},
												remark: {
													value: "",
													color: "#173177"
												}
											}
										});
									}
								});


								res.send("<xml><ToUserName>"+data.xml.FromUserName+"</ToUserName><FromUserName>"+data.xml.ToUserName+"</FromUserName><CreateTime>"+Math.round(new Date().getTime()/1000)+"</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[你已成为 "+user.get("nickname")+"的粉丝啦！]]></Content></xml>");
							}else if(result){
								if(user.id==result.get("uid")){
									res.send("<xml><ToUserName>"+data.xml.FromUserName+"</ToUserName><FromUserName>"+data.xml.ToUserName+"</FromUserName><CreateTime>"+Math.round(new Date().getTime()/1000)+"</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[再爱 "+user.get("nickname")+" ，也只能关注一次啦~]]></Content></xml>");
								}else{
									res.send("<xml><ToUserName>"+data.xml.FromUserName+"</ToUserName><FromUserName>"+data.xml.ToUserName+"</FromUserName><CreateTime>"+Math.round(new Date().getTime()/1000)+"</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[你是别人的粉丝了，请不要三心二意哦~]]></Content></xml>");
								}
							}else{
								res.send("success");
							}
						},function(error){
							if(typeof(error)=="object")error=error.message;
							console.error(error);
							res.send("success");
						});

					}else{
						if(data.xml.Event=="subscribe"){
						//console.log(EventKey);
							var sn=EventKey-1000;
							var queryExtendQRCode		= new AV.Query(avExtendQRCode);
							queryExtendQRCode.equalTo("sn",sn);
							queryExtendQRCode.first(function(result){
								//console.dir(result);
								if(typeof(result)=="object"){
									result.addUnique('openidArr', data.xml.FromUserName);
									result.save();
								}
							},function(error){
								if(typeof(error)=="object")error=error.message;
								console.error(error);
							});
						}
						res.send("success");
					}
				}else{
					res.send("success");
				}
			}else if(data && data.xml.MsgType=="text"){
				if(data.xml.Content=="快趣订001"){
					res.send("<xml><ToUserName>"+data.xml.FromUserName		+"</ToUserName><FromUserName>"+data.xml.ToUserName
					+"</FromUserName><CreateTime>"+Math.round(new Date().getTime()/1000)					+"</CreateTime><MsgType><![CDATA[news]]></MsgType>"
					+"<ArticleCount>1</ArticleCount><Articles><item>"
					+"<Title><![CDATA[快趣订商户后台管理入口]]></Title>"
					+"<Description><![CDATA[点击进入后台]]></Description>"	+"<PicUrl><![CDATA[http://mmbiz.qpic.cn/mmbiz/"	+"eGnI8NERWeP0udsGFAd89ItbEVTJIdSmsG8kRYBdfaJvD7OBGRY5sKrqEAS4E5vMN7Ra3ic94Rr0pG6CFl4y0Ag/640?wx_fmt=jpeg&tp=webp&wxfrom=5]]></PicUrl>"
					+"<Url><![CDATA[http://mp.weixin.qq.com/s?__biz="					+"MzIyOTA3NDE2OQ==&mid=400352381&idx=1&sn=a8a8e4aa2344442ffdf6e75239626d2e]]></Url></item></Articles></xml>");
				}else if(data.xml.Content=="二维码"){
					res.send("<xml><ToUserName>"+data.xml.FromUserName		+"</ToUserName><FromUserName>"+data.xml.ToUserName
					+"</FromUserName><CreateTime>"+Math.round(new Date().getTime()/1000)					+"</CreateTime><MsgType><![CDATA[news]]></MsgType>"
					+"<ArticleCount>1</ArticleCount><Articles><item>"
					+"<Title><![CDATA[快趣订管理员推广码]]></Title>"
					+"<Description><![CDATA[点击查看详情]]></Description>"	+"<PicUrl><![CDATA[http://mmbiz.qpic.cn/mmbiz/"	+"eGnI8NERWeP0udsGFAd89ItbEVTJIdSmsG8kRYBdfaJvD7OBGRY5sKrqEAS4E5vMN7Ra3ic94Rr0pG6CFl4y0Ag/640?wx_fmt=jpeg&tp=webp&wxfrom=5]]>"
					+"</PicUrl><Url><![CDATA[http://kqd.leanapp.cn/bg/share]]></Url>"
					+"</item></Articles></xml>");
				}else{
					res.send("success");
				}
			}else{
				res.send("success");
			}
		});
		//console.dir(req);
	});

}

/**
 * 计算签名
 * 2015.11.03  by 胡斌
 */
exports.getSign = function(json){
	var crypto 	= require('crypto');
	var md5 	= crypto.createHash('md5');
	var stringA="",arr=[],sign;
	for(key in json){
		arr.push(key);
	}
	arr.sort();
	for(var i=0;i<arr.length;i++){
		arr[i]+="="+json[arr[i]];
	}
	stringA=arr.join("&");
	//console.log(stringA);

	stringSignTemp	= stringA+"&key="+exports.appsecret;
	var Buffer = require("buffer").Buffer;
    var buf = new Buffer(stringSignTemp);
    var str = buf.toString("binary");
	//console.log(str);
	md5.update(str);
	var sign=md5.digest('hex').toUpperCase();
	//console.log(sign);
	return sign;
	//return stringSignTemp;
}
